/**
 * 
 */
package us.gaaoc.framework.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;

import us.gaaoc.framework.model.Address;
import us.gaaoc.framework.model.PersonAddress;

/**
 * @author Sukhada Tapshalkar
 *
 * Dec 4, 2007
 *
 * GAJE_BibbCounty_2.0
 *
 */
public class AddressDAOHibernate extends GenericHibernateDAO<Address, Integer,AddressDAO> 
implements AddressDAO{

	protected AddressDAOHibernate() {
		
	}

	/* (non-Javadoc)
	 * @see us.gaaoc.framework.dao.AddressDAO#updateAddress(us.gaaoc.framework.model.Person, us.gaaoc.framework.model.Address)
	 */
	public void updateAddress(Address address, PersonAddress personAddress) {
		// Find the address to update
		Query q = this.getSession().createQuery("from PersonAddress pa where pa.uuid=?");
		String personAddressUuid = personAddress.getUuid();
		q.setEntity(0,personAddressUuid);
		PersonAddress pa = (PersonAddress) q.list().get(0);	
		// Extract the address from the personAddress object
		Address add = (Address)pa.getAddress();
		// Update the Address
		add.setStreetFullText(address.getStreetFullText());
		add.setStreetExtensionText(address.getStreetFullText());
		add.setCityName(address.getCityName());
		add.setState(address.getState());
		add.setZipCode(address.getZipCode());		
		LOG.info("persisting the Address object .....");
		// Save the address back to the database
	    this.makePersistent(add);				
	}
	
	public Address findAddressExactMatch(Address address) {
		String streetText = address.getStreetFullText();
		String streetExtText = address.getStreetExtensionText();
		String city = address.getCityName();
		String state = address.getState();
		String zip = address.getZipCode();
		
		Address matchingAddress = new Address();
		try {
			
			Query q = getSession()
			.createQuery(
					"from Address a where (a.streetFullText = ? " 
					+ " and a.streetExtensionText = ?"
					+ " and a.cityName = ? "
					+ " and a.state = ? "
					+ " and a.zipCode = ?)");
			q.setString(0, streetText);
			q.setString(1, streetExtText);
			q.setString(2, city);
			q.setString(3, state);
			q.setString(4, zip);
			List l = q.list();
			// Only take the first address
			// List used in case of duplicate address entries
			if (!l.isEmpty()) {
				matchingAddress = (Address) l.get(0);
			}
			/*if (!l.isEmpty()) {
				Object[] results = (Object[]) l.get(0);
				matchingAddress.setUuid((String) results[0]);
				matchingAddress.setStreetFullText((String) results[1]);
				matchingAddress.setStreetExtensionText((String) results[2]);
				matchingAddress.setCityName((String) results[3]);
				matchingAddress.setState((String) results[4]);
				matchingAddress.setZipCode((String) results[5]);
			}*/
		} catch (HibernateException e) {
			LOG.error(e);
			throw e;
		}
		return matchingAddress;
	}

	
}
